/*
 * @Author: silence
 * @Date: 2023-07-10 17:08:10
 * @LastEditors: silence silence9685@163.com
 * @LastEditTime: 2023-08-08 13:58:32
 * @Description: 电站列表item
 */

import 'dart:async';

import 'package:ems_neutral_app/entities/DeviceEntity.dart';
import 'package:ems_neutral_app/pages/Mine/Language/LanguageController.dart';
import 'package:ems_neutral_app/pages/PowerStation/Controller/PowerStationController.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/sil_utils_package.dart';
import 'package:sil_utils_package/utils/time/SilTimeUtils.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

import '../../../common/Method/CommonMethod.dart';
import '../../Mine/Language/SilLocalizations/SilLocalizations.dart';

class PsManagerListItem extends StatefulWidget {
  final DeviceEntity deviceEntity;
  const PsManagerListItem({super.key, required this.deviceEntity});

  @override
  State<PsManagerListItem> createState() => _PsManagerListItemState();
}

class _PsManagerListItemState extends State<PsManagerListItem> {
  late TooltipBehavior _tooltip;
  bool _isEditing = false; // 编辑状态
  PowerStationController _controller = Get.put(PowerStationController());

  /// 监听键盘弹出和消失
  late StreamSubscription<bool> keyboardSubscription;

  /// 原来的电站名称
  String? _oldPsName;

  /// 想要修改的站名称
  String? _newPsName;

  /// 是否重命名
  bool _isRename = false;

  late ValueKey _textFieldKey;

  @override
  void initState() {
    super.initState();

    _tooltip = TooltipBehavior(enable: true);
    _oldPsName = widget.deviceEntity.psName;
    _newPsName = _oldPsName;
    initTextField();

    var keyboardVisibilityController = KeyboardVisibilityController();

    // 监听键盘弹出和消失
    keyboardSubscription =
        keyboardVisibilityController.onChange.listen((bool visible) {
      print('Keyboard visibility update. Is visible: $visible');

      /// 没有重命名，键盘隐藏时，名称恢复原来的
      if (visible == false && _isRename == false && _newPsName != _oldPsName) {
        initTextField();
        setState(() {});
      }
    });
  }

  initTextField() {
    _newPsName = _oldPsName;
    _textFieldKey = ValueKey(SilTimeUtils.currentTimeMillis());
  }

  @override
  void dispose() {
    keyboardSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        SilEmptyButton(
          behavior: HitTestBehavior.translucent,
          useConstrained: true,
          backgroundColor: ColorUtils.hexColor('#4d4d4d'),
          padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 13.w),
          radius: 8.w,
          child: contentView(),
          onTapFunc: () {
            _isEditing = !_isEditing;
            setState(() {});
          },
        ),
        if (_isEditing) // 编辑状态
          Positioned(
              top: -10.w,
              right: -5.w,
              child: Container(
                width: 20.w,
                height: 20.w,
                child: SilButton(
                  imgPath: 'imgs/set/set_cancel_red.png',
                  width: 20.w,
                  height: 20.w,
                  onTapFunc: handlerDelEvent,
                ),
              )),
      ],
    );
  }

  /// 处理删除电站
  handlerDelEvent() {
    if (_controller.myPowerStationList.length > 1) {
      _controller.requestPowerStationDelete(
          context: context, deviceId: widget.deviceEntity.id);
      return;
    }

    /// 最后一个电站不能删除
    LanguageController languageController = LanguageController();
    bool isPromptEnglish = languageController.isPromptEnglish();
    String? alertTitle = isPromptEnglish
        ? "The last power station can not be deleted"
        : "最后一个电站了，不能删除";
    String? alertCancelTitle = LangOf(context)?.common?.cancel;
    String? alertConfirmTitle = LangOf(context)?.common?.confirm;

    /// 弹窗确认
    SilAlertDialog.showAlertDialog(
      context,
      SilAlertDialogData(
          title: alertTitle,
          cancelButtonTitle: alertCancelTitle,
          confrimButtonTitle: alertConfirmTitle),
    );
  }

  contentView() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        titleView(),
        realTimePowerView(),
        SilText(
          LangOf(context)?.userDz_setting?.electricity,
          fontSize: 12.w,
          color: ColorUtils.color_subtitle,
        ),
      ],
    );
  }

  titleView() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
            child: AbsorbPointer(
                absorbing: false, //!_isEditing,
                child: SilTextField(
                    key: _textFieldKey,
                    height: 14.w,
                    showClearBtn: false,
                    interface: SilFormattersNickName(),
                    onValid: (valid, value) {
                      _newPsName = value;
                    },
                    text: _newPsName,
                    hintText: '',
                    textInputAction: TextInputAction.done,
                    onEditingComplete: () {
                      _isRename = true;
                      handlerRenameEvent();
                    },
                    textStyle: TextStyle(
                        fontSize: 13.w,
                        color: ColorUtils.hexColor('#ececec'))))),
        SilImage(
          'imgs/set/set_edit.png',
          height: 20.w,
          width: 20.w,
        )
      ],
    );
  }

  /// 处理修改电站名称
  handlerRenameEvent() {
    // 隐藏键盘
    globalTextFieldDismiss(context);

    _controller.requestPowerStationRename(
      context: context,
      name: _newPsName,
      psId: widget.deviceEntity.id!,
      successHandler: (p0) {
        _oldPsName = _newPsName;
        _isRename = false;
      },
      failure: () {
        _isRename = false;
        initTextField();
        setState(() {});
      },
    );
  }

  /// 实时功率
  realTimePowerView() {
    double realPowerPer = widget.deviceEntity.surplusPowerPer;
    return Container(
      height: 120.w,
      width: 120.w,
      child: Stack(
        alignment: Alignment.center,
        children: [
          circleView(value: realPowerPer),
          Container(
              padding: EdgeInsets.symmetric(horizontal: 22.w),
              alignment: Alignment.center,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SilText(
                    '$realPowerPer',
                    fontSize: 14.sp,
                    color: ColorUtils.color_font_main,
                    margin: EdgeInsets.only(bottom: 3.w),
                    maxLines: 0,
                    textAlign: TextAlign.center,
                  ),
                  SilText(
                    '%',
                    fontSize: 14.sp,
                    color: ColorUtils.color_font_main,
                  ),
                ],
              )),
        ],
      ),
    );
  }

  circleView({double value = 0, String circleColor = '#09bcd6'}) {
    double radius = 84.w / 2;
    double innerRadius = radius - 4.5.w;
    return SfCircularChart(
      // backgroundColor: Colors.lightGreen,
      tooltipBehavior: _tooltip,
      margin: EdgeInsets.zero,
      series: <CircularSeries>[
        RadialBarSeries<_ChartData, String>(
          legendIconType: LegendIconType.circle,
          dataSource: [_ChartData('', value)],
          xValueMapper: (_ChartData data, _) => data.name,
          yValueMapper: (_ChartData data, _) => data.y,
          pointColorMapper: (datum, index) => ColorUtils.hexColor(circleColor),
          trackColor: ColorUtils.hexColor('#ffffff'),
          innerRadius: "$innerRadius",
          radius: '$radius',
          enableTooltip: false, // 不显示提示
          cornerStyle: CornerStyle.bothFlat,
          maximumValue: 100,
        ),
      ],
    );
  }
}

class _ChartData {
  _ChartData(this.name, this.y);

  final String name;
  final double y;
}
